package com.lzy.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BigFileMD5 {

    static MessageDigest MD5 = null;
    static List<File> list = new ArrayList<File>();
    static{
        try{
            MD5 = MessageDigest.getInstance("MD5");
        }catch(NoSuchAlgorithmException e){
            log.error(e.toString());
        }
    }

    /**
     * 对一个文件获取md5值
     * @return md5串
     */
    public static String getStreamMD5(InputStream fileInputStream) {
        try {
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }

            return new String(Hex.encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
            log.error(e.toString());
            return null;
        } catch (IOException e) {
            log.error(e.toString());
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                log.error(e.toString());
            }
        }
    }

    /**
     * 对一个文件获取md5值
     * @return md5串
     */
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }

            return new String(Hex.encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
            log.error(e.toString());
            return null;
        } catch (IOException e) {
            log.error(e.toString());
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                log.error(e.toString());
            }
        }
    }
}
